chromosome.h
#define MAX_BITS_PER_GENE 8
typedef struct chromo_tag
{
unsigned int bits_per_gene;
unsigned int gene_num;
char * data_p;
} chromo_t;
int init_chromo( chromo_t *chromo_p, unsigned int bits_per_gene, unsigned int gene_num );
int free_chromo( chromo_t *chromo_p );
char get_gene( chromo_t *chromo_p, unsigned int gene_index );
int set_gene( chromo_t *chromo_p, unsigned int gene_index, char new_gene );
population.h
#include "chromosome.h"
#define BITS_PER_GENE 2 // todo1: muti gene. todo2: input from config file
#define GEN_NUM 30 // todo1: muti gene. todo2: input from config file
#define MOVE_UP (char)0x00
#define MOVE_DOWN (char)0x40
#define MOVE_LEFT (char)0x80
#define MOVE_RIGHT (char)0xC0
#define MAX_GENERATION 1000
#define MutationRate 0.001
#define CrossoverRate 0.7
typedef struct individual_tag
{
chromo_t chromo;
float score; // the score of the individual(0~100)
}individual_t;
typedef struct population_tag
{
individual_t *individual_array;
unsigned int individual_num;
}population_t;
typedef struct rouletteWheelPiece_tag
{
float low;
float high;
}piece_t;
typedef struct rouletteWheel_tag
{
unsigned int num;
piece_t *data_p;
}rouletteWheel_t;
int init_population( population_t *popu_p, unsigned int individual_num);
int free_population( population_t *popu_p );
int crossover( population_t *parents_p, population_t *children_p );
int updateScore( individual_t *indi );
int mutation( population_t *parents_p );
#include "common.h"
#include "chromosome.h"
int init_chromo( chromo_t *chromo_p, unsigned int bits_per_gene, unsigned int gene_num )
{
unsigned int size = ( bits_per_gene * gene_num + 8 ) / 8;
chromo_p->bits_per_gene = 0;
chromo_p->data_p = NULL;
chromo_p->gene_num = 0;
if( MAX_BITS_PER_GENE < bits_per_gene )
{
error_output( "Too long bits per gene." );
return 1;
}
chromo_p->data_p = malloc( size );
if( chromo_p->data_p == NULL )
{
error_output( "init_chomo: malloc fail." );
return 1;
}
memset(chromo_p->data_p, 0, size);
chromo_p->bits_per_gene = bits_per_gene;
chromo_p->gene_num = gene_num;
return 0;
}
int free_ch